import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;

import java.net.Authenticator;
import java.net.PasswordAuthentication;

class MyAuthenticator extends Authenticator
{
	/**
	 * Called when password authorization is needed.
	 * @return The PasswordAuthentication collected from the
	 * user, or null if none is provided.
	 */
	protected PasswordAuthentication getPasswordAuthentication()
	{
		return new PasswordAuthentication ( "hnav-vendor", "SUspuC%9".toCharArray() );
	}
}

public class test {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static int z = 0;
    static HashMap validSymbolRates = new HashMap();
	static {
		//System.out.println("class static");
		
	}
	
	public static void main(String[] args) throws Exception {

		// TODO Auto-generated method stub

		/*int appid = 0x34;
		System.out.println(appid);
		if (appid == 0x34)
		{
			System.out.println("true");
		}
		
		File f = new File("test.txt");
		f.createNewFile();
		System.out.println(f.exists());
		
		System.out.println(f.getCanonicalPath());
		
		
		double d = 323343/10000;
		
		System.out.println(d);*/
		
		//ua();
		
//		String ua = "123-45678-12345-999";
//		StringTokenizer st = new StringTokenizer(ua, "-");
//		
//		while(st.hasMoreTokens()) 
//		{ 
//			String key = st.nextToken(); 
//			System.out.println(key); 
//		} 
		
//		String serial = "M11152TF8226";
//		long l = 123 * 12345 * 45678 * 123;
//		System.out.println(l);
		
		//old_ua();
		
//		try {
//			sslServer();
//			Thread.sleep(1000);
//			sslClient();
//		} catch (Throwable e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		//File f = new File(".");
		//System.out.println(f.getPath());
//		
		
//		float f = -10.2f;
//		System.out.println(f);
//		System.out.println(Math.abs(f));
		
//		String url = "http://10.13.223.64:8080?wsurl=ws://10.13.223.64:8080";
//		try {
//			new URL(url);
//		} catch (MalformedURLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
		
		//String[] a = new String[] {"a","b"};
		//System.out.println("a = "+ a != null ? "1" : "2");
		

		//System.out.println("inside main");
		//x1();
		
		//System.out.println(Integer.parseInt(""));
		
		//findServers();
		
		//System.out.println(testCatch());
		
//		int a=1;
//		int b=2;
//		
//		if (a==1)
//		{
//			System.out.println("1");
//		}
//		else if (b==2)
//		{
//			System.out.println("2");
//		}
//		else
//		{
//			System.out.println("3");
//		}
//		final int SCTE_MODULATION_64 = 8;
//		final int SCTE_MODULATION_256 = 16;
//		final int SCTE_MODULATION_QPSK = 1;
//		  final int VALID_SYMBOL_RATE_FOR_QAM64  = 5056;
//		  final int VALID_SYMBOL_RATE_FOR_QAM256 = 5360;
//		  final int VALID_SYMBOL_RATE_1_FOR_QPSK = 1024;
//		  final int VALID_SYMBOL_RATE_2_FOR_QPSK = 772;
//		  final int VALID_SYMBOL_RATE_3_FOR_QPSK = 1544;
//
//	    ArrayList symbolRatesForQAM64 = new ArrayList();
//	    symbolRatesForQAM64.add(new Integer(VALID_SYMBOL_RATE_FOR_QAM64));
//
//	    ArrayList symbolRatesForQAM256 = new ArrayList();
//	    symbolRatesForQAM256.add(new Integer(VALID_SYMBOL_RATE_FOR_QAM256));
//
//	    ArrayList symbolRatesForQPSK = new ArrayList();
//	    symbolRatesForQPSK.add(new Integer(VALID_SYMBOL_RATE_1_FOR_QPSK));
//	    symbolRatesForQPSK.add(new Integer(VALID_SYMBOL_RATE_2_FOR_QPSK));
//	    symbolRatesForQPSK.add(new Integer(VALID_SYMBOL_RATE_3_FOR_QPSK));
//	    validSymbolRates.put(new Integer(SCTE_MODULATION_64), symbolRatesForQAM64);
//	    validSymbolRates.put(new Integer(SCTE_MODULATION_256), symbolRatesForQAM256);
//	    validSymbolRates.put(new Integer(SCTE_MODULATION_QPSK), symbolRatesForQPSK);
//	    
//	    System.out.println(isSymbolRateValid(0,0));
		
/*		String message = "POWER=ON,DATA=ON,";
		StringTokenizer parser = new StringTokenizer(message,"=,");

        while (parser.hasMoreTokens())
		{
			try {
                String indicator = parser.nextToken();
                System.out.println("indicator is " + indicator  );
                //String n = parser.nextToken("=");
                //System.out.println("n "  +n);
                String mode = parser.nextToken();
                System.out.println("mode is " + mode);
            } catch (NoSuchElementException e) {
                throw new Exception("Incorrect poor FP message format: "
                        + message);
            }
		}*/
		
//		System.out.println("Hello World!");
//		class A 
//		{
//			A(){}
//			boolean solution(int A[],int K)
//			{
//				int n = A.length;
//				 for (int i = 0; i < n - 1; i++) {
//					 if (A[i] + 1 < A[i + 1])
//						 return false;
//				 }
//			
//				 if (A[0] != 1 && A[n - 1] != K)
//					 return false;
//				 else
//					 return true;
//
//			}
//		}
//		A a = new A();
//		int arr[] = {1,1,2,2,3,4};
//		//int arr[] = {1};
//		System.out.println(a.solution(arr,3));
//		
//		int arr1[] = {1,1,2,2,3,3};
//		System.out.println(a.solution(arr1,2));
		
		ArrayList<Integer> test = new ArrayList<Integer>(Arrays.asList( 1, 2, 3, 4, 5, 6, 7, 8, 9 ));

		int w = 0;
		while ( w < 100)
		{
			Collections.shuffle(test, new Random()) ;
			for (Integer q : test)  
		    {  
		       System.out.print(q + " ");  
		    } 
			System.out.println();
			w++;
		}

		
		
	    
	}
	

		
	private static char[] testCatch() {
		// TODO Auto-generated method stub
		try {
			System.out.println("reached here 1");
			throw new Exception("chra");
		}
		catch (Exception e)
		{
			System.out.println("reached here 2");
			return null;
		}
		finally
		{
			System.out.println("reached here 3");
		}
		//System.out.println("reached here 4");
		//return null;
	}


	static boolean
	isSymbolRateValid(int m, int sr) {
	    List symbolRates = (ArrayList)validSymbolRates.get(new Integer(m));
	    System.out.println(symbolRates);
	    return symbolRates.contains(new Integer(sr));
	}
	
	private static void findServers()
	{
		String urla = "https://pi-eng.timewarnercable.com/hnavc/0.";
//		34.2
		String urlb = "-BETA/index.html";
		double version = 60.0;

		double finVersion = version + 20.0;
		for (double i = version; i < finVersion; i=version=version+0.1 )
		{
			DecimalFormat f = new DecimalFormat("##.0"); 
			String url = urla + f.format(i) + urlb;

			try {
				URL u = new URL(url  );
				
				HttpsURLConnection http = (HttpsURLConnection) u.openConnection();

				Authenticator.setDefault( new MyAuthenticator() );
	            http.setAllowUserInteraction(true);
	            http.setRequestMethod("GET");
	            http.connect();

//	            InputStream is = http.getInputStream();
//	            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//	            StringBuilder stringBuilder = new StringBuilder();
//	            String line = null;
//	            while ((line = reader.readLine()) != null)
//	            {
//	                stringBuilder.append(line + "\n");
//	            }
//	            System.out.println(stringBuilder.toString());    
				
				
				int code = http.getResponseCode();
				if (code != 404)
					System.out.println(url +" ====== " + code);
				//else
					//System.out.println(f.format(i) + " " + code);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
		} 
	}
	
	private static void x1() {
		// TODO Auto-generated method stub
		System.out.println("x1 static");
	}

	static public int sslServer() throws Throwable 
	   {
		   (new Thread("sslServerThread") {
			   public void run() {
				   try 
				   {
					   SSLServerSocketFactory sslserversocketfactory = getSSLServerSocketFactory();
							  // (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); -- for JavaVM
					   
					   SSLServerSocket sslserversocket =
							   (SSLServerSocket) sslserversocketfactory.createServerSocket(15245);
					   
					   System.out.println("SOCKET CREATED");
					   SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();
					   
					   String[] cipherSuites = sslsocket.getSupportedCipherSuites();
					   for( int i = 0; i < cipherSuites.length; i++)
						   System.out.println("===================================" +cipherSuites[i]);
					   sslsocket.setEnabledCipherSuites(cipherSuites);
					   
					   InputStream inputstream = sslsocket.getInputStream();
					   InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
					   BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

					   String string = null;
					   while ((string = bufferedreader.readLine()) != null) 
					   {
						   System.out.println(string);
						   System.out.flush();
					   }
				   }
				   catch (Exception ex) 
				   {
					   ex.printStackTrace();
				   }
			   }
		   }).start();

		   return 1;
	   }
	   
	   static public int sslClient() throws Throwable
	   {
		   try 
		   {
	           SSLSocketFactory sslsocketfactory = getSSLSocketFactory();//(SSLSocketFactory) SSLSocketFactory.getDefault(); -- for JavaVM
	           SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket("localhost", 15245);
	           String str = "==================$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$This is a test for SSL communication between sockets";

	           String[] cipherSuites = sslsocket.getSupportedCipherSuites();
			   sslsocket.setEnabledCipherSuites(cipherSuites);
			   
	           InputStream inputstream = new ByteArrayInputStream(str.getBytes());
	           InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
	           BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

	           OutputStream outputstream = sslsocket.getOutputStream();
	           OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
	           BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);

	           String string = null;
	           while ((string = bufferedreader.readLine()) != null) 
	           {
	               bufferedwriter.write(string + '\n');
	               bufferedwriter.flush();
	           }
			   outputstreamwriter.flush();
			   
	       }
		   catch (Exception ex) 
		   {
	           ex.printStackTrace();
	       }
		   
		   return 1;
	   }
	   
		private static TrustManager[] getTrustManagers(String location, String password)
				throws IOException, GeneralSecurityException {
			// First, get the default TrustManagerFactory.
			String alg=TrustManagerFactory.getDefaultAlgorithm();
			TrustManagerFactory tmFact=TrustManagerFactory.getInstance(alg);
		 
			FileInputStream fis=new FileInputStream(location);
			KeyStore ks=KeyStore.getInstance("bks");
			ks.load(fis, password.toCharArray());
			fis.close();
		 
			tmFact.init(ks);
		 
			// And now get the TrustManagers
			TrustManager[] tms=tmFact.getTrustManagers();
			return tms;
		}
	   
	   
	   private static SSLServerSocketFactory getSSLServerSocketFactory()
	   {
		   try {
			   // SSLContext protocols: TLS, SSL, SSLv3
			   SSLContext sc = SSLContext.getInstance("SSLv3");
			   
										   //********************* DEBUG **********************/
										   System.out.println("\nSSLContext class: "+sc.getClass());
										   System.out.println("   Protocol: "+sc.getProtocol());
										   System.out.println("   Provider: "+sc.getProvider());
										   //********************* DEBUG **********************/
			   
			   
			   // SSLContext algorithms: X.509
			   KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			   
										   //********************* DEBUG **********************/
										   System.out.println("\nKeyManagerFactory class: " +kmf.getClass());
										   System.out.println("   Algorithm: "+kmf.getAlgorithm());
										   System.out.println("   Provider: "+kmf.getProvider());
										   //********************* DEBUG **********************/
			   
			   // KeyStore types: BKS
			   String ksName = "./keystore.bks";
			   char ksPass[] = "password".toCharArray();
			   char ctPass[] = "password".toCharArray();
			   
			   KeyStore ks = KeyStore.getInstance("BKS");
			   ks.load(new FileInputStream(ksName), ksPass);
			   
										   //********************* DEBUG **********************/
										   System.out.println("\nKeyStore class: "+ks.getClass());
										   System.out.println("   Type: "+ks.getType());
										   System.out.println("   Provider: "+ks.getProvider());
										   System.out.println("   Size: "+ks.size());
										   //********************* DEBUG **********************/
			   
			   // Generating KeyManager list
			   kmf.init(ks,ctPass);
			   KeyManager[] kmList = kmf.getKeyManagers();
			   
										   //********************* DEBUG **********************/
										   System.out.println("\nKeyManager class: "  +kmList[0].getClass());
										   System.out.println("   # of key manager: " +kmList.length);
										   //********************* DEBUG **********************/
										   
	           TrustManager tm[] = getTrustManagers("./keystore.bks", "password");										
										   
	   		   // Generating SSLServerSocketFactory
			   sc.init(kmList, tm, null);
			   SSLServerSocketFactory ssf = sc.getServerSocketFactory();

	                                         		                   System.out.println("\nSSLServerSocketFactory class: " +ssf.getClass());


			   return ssf;
		   } catch (Exception e) {
			   // TODO Auto-generated catch block
			   e.printStackTrace();
		   }
		   
		return null;
	   }
	   
	   private static SSLSocketFactory getSSLSocketFactory()
	   {
		   try {
			   // SSLContext protocols: TLS, SSL, SSLv3
			   SSLContext sc = SSLContext.getInstance("SSLv3");
			   
										 //********************* DEBUG **********************/
										   System.out.println("\nSSLContext class: "+sc.getClass());
										   System.out.println("   Protocol: "+sc.getProtocol());
										   System.out.println("   Provider: "+sc.getProvider());
										 //********************* DEBUG **********************/
			   // SSLContext algorithms: X.509
			   KeyManagerFactory kmf 
			   = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			   
										 //********************* DEBUG **********************/
										   System.out.println("\nKeyManagerFactory class: " +kmf.getClass());
										   System.out.println("   Algorithm: "+kmf.getAlgorithm());
										   System.out.println("   Provider: "+kmf.getProvider());
										 //********************* DEBUG **********************/
										   
			   // KeyStore types: BCKS
			   String ksName = "./keystore.bks";
			   char ksPass[] = "password".toCharArray();
			   char ctPass[] = "password".toCharArray();
			   KeyStore ks = KeyStore.getInstance("BKS");
			   ks.load(new FileInputStream(ksName), ksPass);
			   
										 //********************* DEBUG **********************/
										   System.out.println("\nKeyStore class: "+ks.getClass());
										   System.out.println("   Type: "+ks.getType());
										   System.out.println("   Provider: "+ks.getProvider());
										   System.out.println("   Size: "+ks.size());
										 //********************* DEBUG **********************/
			   
			   // Generating KeyManager list
			   kmf.init(ks,ctPass);
			   KeyManager[] kmList = kmf.getKeyManagers();
			   
										 //********************* DEBUG **********************/
										   System.out.println("\nKeyManager class: "  +kmList[0].getClass());
										   System.out.println("   # of key manager: " +kmList.length);
										 //********************* DEBUG **********************/
								   
			   TrustManager tmList[] = getTrustManagers("./keystore.bks", "password");																	   
			   sc.init(kmList, tmList, null);
			   SSLSocketFactory sf = sc.getSocketFactory();
			   
			   								System.out.println("\nSSLSocketFactory class: " +sf.getClass());

			   return sf;
		   } catch (Exception e) {
			   // TODO Auto-generated catch block
			   e.printStackTrace();
		   }
		   return null;
	   }
	   

	
	
	private static void old_ua() throws Exception
	{
		final String[] ua = readLines("ua.txt");
		File f = new File("time.csv");
		f.createNewFile();
		FileWriter fw = new FileWriter(f.getAbsoluteFile());
		bw = new BufferedWriter(fw);
		long originaltime;
		long time = originaltime = System.currentTimeMillis();
		
		for (int i = 0; i < ua.length; i++)
		{
			//Long lo = Long.parseLong(ua[z++].trim());
			Random r = new Random(time += 1);
			long l = r.nextLong();
			//int l = r.nextInt(14400);
			if (l < 0) l = -(l);
			long waitInMill = l % 14400000L;
			waitInMill += 900000L;
			
			try {
				bw.write(time-originaltime + "," + waitInMill / 1000);
				bw.newLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				break;
			}
			bw.flush();
			System.out.println(time-originaltime + "," + waitInMill / 1000);
		}
		
	}
	
	static BufferedWriter bw = null;
	private static void ua() throws Exception {
		final String[] ua = readLines("ua.txt");
		//final String[] ua = {"0000045833101135"};
		//final String[] serial = readLines("serial.txt");
		//System.out.println(serial[0]);
		//System.out.println(serial[0].replaceAll("[^\\d]", ""));
		
		//Integer.parseInt("00002342342");
		//System.exit(1);
		//final Long lo = System.currentTimeMillis();
		//for (int i = 0; i < 1000; i++)
		File f = new File("out.txt");
		f.createNewFile();
		FileWriter fw = new FileWriter(f.getAbsoluteFile());
		bw = new BufferedWriter(fw);
		
		for (int i = 0; i < ua.length; i++)
		{
			Long lo = Long.parseLong(ua[z++].trim());
			//lo *= Integer.parseInt(serial[z++].replaceAll("[^\\d]", ""));
			Random r = new Random(lo);
			//long l = r.nextLong();
			int l = r.nextInt(14400);
			if (l < 0) l = -(l);
			//long waitInMill = l % 7200000L;
			l += 900L;
			
			try {
				bw.write("" + l);
				bw.newLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				break;
			}
			bw.flush();
			System.out.println(l);
			(new Thread() {
				public void run() {
					
				}
			}).start();
		}
	}

	public static String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
}
